<template>
  <div>
    <!-- {{ $store.state.routerLimits }} -->
    <div slot="header" class="clearfix">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="角色名称">
          <el-input
            clearable
            v-model="formInline.name"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="add">新增角色</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="body">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        fit
        max-height="600"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="100"> </el-table-column>
        <el-table-column prop="name" label="角色名称"> </el-table-column>
        <el-table-column prop="ctime" label="创建时间" width="200">
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-button @click="checkOrder(scope.$index, scope.row)" size="mini"
              >权限</el-button
            >
            <el-button @click="deletee(scope.$index, scope.row)" size="mini"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40, 50, 60]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      title="添加角色"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="beforeClose"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.name" style="width: 50%"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="配置权限"
      :visible.sync="dialogVisible1"
      width="30%"
      :before-close="beforeClose"
    >
      <el-tree
        :data="treelist"
        node-key="id"
        show-checkbox
        :default-checked-keys="checkList"
        @check-change="handleCheckChange"
        @check="handleCheck"
        ref="rightsTree"
        :props="defaultProps"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="save()">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  roleList,
  addRole,
  getAuthority,
  setRole,
  deleteRole,
} from "../../../utils/api";

export default {
  name: "roleList",
  data() {
    return {
      formInline: {
        name: "",
      },
      token: sessionStorage.getItem("token"),
      loading: false,
      tableData: [],
      limit: 10,
      currentPage: 1,
      total: 0,
      iflag: false,
      dialogVisible: false,
      dialogVisible1: false,
      form: { name: "" },
      checkList: [],
      treelist: [],
      defaultProps: {
        children: "son",
        label: "name",
      },
      chooseJuese: {},
      parentList: [],
      childList: [],
    };
  },
  methods: {
    closeDialog() {
      this.dialogVisible = false;
      this.dialogVisible1 = false;
      this.form = { name: "" };
      this.checkList = [];
      this.chooseJuese = {};
    },
    handleCheckChange(data, checked, indeterminate) {
      if (checked) {
        if (this.checkList.indexOf(data.id) == -1) {
          this.checkList.push(data.id);
        }
      } else {
        if (this.checkList.indexOf(data.id) != -1) {
          this.checkList.splice(
            this.checkList.indexOf(data.id),
            this.checkList.indexOf(data.id) + 1
          );
        }
      }
    },
    handleCheck(data, obj) {
      // this.routerList
      this.parentList = obj.halfCheckedNodes.map((item) => item.id);
      this.childList = obj.checkedNodes.map((item) => item.id);
      console.log("parentList", this.parentList);
      console.log("childList", this.childList);
      // console.log(data, obj);
    },
    save() {
      let str = "";
      this.checkList.forEach((item) => {
        str += item + ",";
      });
      str = str.slice(0, str.length - 1);
      const parentRouterList = this.parentList.join(",");
      const childRouterList = this.childList.join(",");
      // console.log(this.checkList);
      // const routerList = this.parentList.concat(this.childList);
      // console.log("routerList", routerList);
      setRole(
        this.token,
        this.chooseJuese.name,
        parentRouterList,
        childRouterList,
        this.chooseJuese.id
      ).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
          this.checkList = [];
          this.getList();
        } else {
          this.$message.error(res.data.msg);
        }
      });
      this.chooseJuese = {};
      this.checkList = [];
      this.dialogVisible1 = false;
    },
    beforeClose() {
      this.dialogVisible = false;
      this.dialogVisible1 = false;
      this.form = { name: "" };
      this.checkList = [];
      this.chooseJuese = {};
    },
    getNowTime(time) {
      let date = new Date(time);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      let hour = date.getHours();
      let minute = date.getMinutes();
      let seconds = date.getSeconds();
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      hour = hour < 10 ? "0" + hour : hour;
      minute = minute < 10 ? "0" + minute : minute;
      seconds = seconds < 10 ? "0" + seconds : seconds;
      return (
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hour +
        ":" +
        minute +
        ":" +
        seconds
      );
    },
    confirm() {
      console.log(21);
      if (this.form.name) {
        addRole(this.token, this.form.name, "").then((res) => {
          if (res.data.status) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.getList();
            this.form = { name: "" };
            this.dialogVisible = false;
          } else {
            this.$message.error(res.data.msg);
          }
        });
      } else {
        this.$message.error("请输入角色名称");
      }
    },
    getList() {
      this.loading = true;
      roleList(
        this.token,
        this.currentPage,
        this.limit,
        this.formInline.name
      ).then((res) => {
        if (res.data.status) {
          this.tableData = res.data.data.data;
          this.total = res.data.data.count;

          let timer = setTimeout(() => {
            this.loading = false;
            clearTimeout(timer);
          }, 400);
        } else {
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
          }
          let timer = setTimeout(() => {
            this.$message.error(res.data.msg);
            this.loading = false;
          }, 400);
        }
      });
    },
    add() {
      this.dialogTitle = "添加角色";
      this.dialogVisible = true;
    },
    search() {},
    handleSelectionChange() {},
    checkOrder(index, row) {
      // row.limits_id.split(",").forEach((item) => {
      //   if (item != "") {
      //     this.checkList.push(Number(item));
      //   }
      // });
      let obj = JSON.parse(JSON.stringify(row));
      // console.log("obj", obj);
      this.chooseJuese = obj;
      // console.log(this.parentList, "====", this.childList);
      // console.log(this.chooseJuese);
      if (this.chooseJuese.limits_id.length <= 1) {
        if (this.chooseJuese.limits_id.length == 1) {
          this.checkList.push(Number(this.chooseJuese.limits_id));
        }
        this.$nextTick(() => {
          this.$refs.rightsTree.setCheckedKeys(this.checkList);
        });
      } else {
        this.chooseJuese.limits_id.split(",").forEach((item) => {
          if (item != "") {
            this.checkList.push(Number(item));
          }
        });
        // =====================================================一下是默认选中节点的处理
        // const inputString = "3,154=1,22,28,258";
        const childIndex = obj.limit_id.indexOf("=");
        // const valuesArray=[]
        if (childIndex !== -1) {
          const childString = obj.limit_id.slice(childIndex + 1);
          const childtArray = childString
            .split(",")
            .map((item) => parseInt(item, 10));
          console.log(childtArray);
          this.checkList = childtArray;
          // 如果点击权限没有更改权限，就默认为子节点（child_ids）还是之前的
          if (this.childList.length == 0) {
            this.childList = childtArray;
          }
          // ===================================================\
          const parentString = obj.limit_id.slice(0, childIndex);
          const parentArray = parentString
            .split(",")
            .map((item) => parseInt(item, 10));
          console.log(parentArray);
          // 如果点击权限没有更改权限，就默认为父节点（parent_ids）还是之前的
          if (this.parentList.length == 0) {
            this.parentList = parentArray;
          }
        } else {
          console.log("No '=' found in the input string.");
        }
        // =================================================================
        // this.checkList = valuesArray;
        // console.log(this.checkList);
        this.$nextTick(() => {
          this.$refs.rightsTree.setCheckedKeys(this.checkList);
        });
      }
      this.dialogVisible1 = true;
    },
    deletee(index, row) {
      this.$confirm("此操作将删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(this.tableData);
          deleteRole(this.token, row.id).then((res) => {
            if (res.data.status) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              if (this.tableData.length <= 1) {
                if (this.currentPage >= 1) {
                  this.currentPage -= 1;
                } else {
                  this.currentPage == 1;
                }
              }
              this.getList();
            } else {
              this.$message.error(res.data.msg);
            }
          });
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
        })
        .catch(() => {
          this.id = "";
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSizeChange(val) {
      this.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },
    onSubmit() {
      this.getList();
    },
  },
  mounted() {
    this.getList();
    getAuthority(this.token).then((res) => {
      if (res.data.status) {
        this.treelist = res.data.data;
      } else {
        this.$message.error(res.data.msg);
      }
    });
  },
};
</script>

<style scoped>
/deep/.header {
  background: white !important;
  box-shadow: 0 5px 10px #ddd;
  min-height: 40px;
  display: flex;
  padding: 10px;
}
.top-input {
  width: 150px;
  margin-right: 20px;
}
.body {
  margin: 20px 0;
}
/deep/.el-table th.el-table__cell > .cell {
  text-align: center;
}
/deep/.el-table .cell {
  text-align: center;
}
.clearfix {
  margin-top: 20px;
}
</style>
